﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Polaris.Common;
using Polaris.Common.FilterAttribute;
using Polaris.Domain.Interfaces.Admin;
using Polaris.Domain.Model.Constant;
using Polaris.Domain.Model.Dto;
using Polaris.Domain.Model.Dto.Sys_User.Request;
using Polaris.Domain.Model.Entity.Exception;
using Polaris.Domain.Model.Entity.Jwt;
using Polaris.Domain.Model.Enum;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection;
using System.Security.Claims;
using System.Text;

namespace Polaris.WebApi.Controllers.Admin
{
    /// <summary>
    /// 用户接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class Sys_UserController : BaseController
    {
        private readonly ISys_User _sysUser;
        private static string? _code;
        private string _defHead = "";

        public Sys_UserController(ISys_User sysUser)
        {
            _sysUser = sysUser;
        }

        /// <summary>
        /// 获取默认头像
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetDefUserHead()
        {
            return SUCCESS(_defHead);
        }

        /// <summary>
        /// 获取所有控制器及接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [CustomAuthorize(Role = RoleConstant.Administrator)]
        public IActionResult GetControllerList()
        {
            // 获取当前程序集中所有的控制器
            var assembly = Assembly.GetExecutingAssembly();
            var controllerTypes = assembly.GetTypes()
                .Where(type => typeof(ControllerBase).IsAssignableFrom(type) && !type.IsAbstract);

            var controllers = new List<ControllerInfoDto>();

            foreach (var controllerType in controllerTypes)
            {
                var controllerName = controllerType.Name.Replace("Controller", "");

                var actions = controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                    .Where(m => typeof(IActionResult).IsAssignableFrom(m.ReturnType) && !m.IsSpecialName)
                    .Select(m => controllerName + "/" + m.Name)
                    .ToList();

                var controllerInfo = new ControllerInfoDto
                {
                    ControllerName = controllerName,
                    Actions = actions
                };

                controllers.Add(controllerInfo);
            }

            return Ok(controllers);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(Domain.Model.Dto.Sys_User.Request.LoginRequest login)
        {
            var user = await _sysUser.Login(login);

            //var claims = ClaimType.user;
            var claims = ClaimType.GetClaims(RoleType.User).WithUserId(user.UserId);
            //switch (user.UserRole)
            //{
            //    case (int)UserRole.User:
            //        claims = ClaimType.user;
            //        break;
            //    case (int)UserRole.Admin:
            //        claims = ClaimType.administrator;
            //        break;
            //}

            JwtSecurityToken token = new JwtSecurityToken(
                          issuer: AppConfig.GetConfigInfo("JwtTokenOptions:Issuer"),
                          audience: AppConfig.GetConfigInfo("JwtTokenOptions:Audience"),
                          claims: claims,
                          expires: DateTime.Now.AddDays(7),
                          signingCredentials: new SigningCredentials(
                              new SymmetricSecurityKey(
                              Encoding.UTF8.GetBytes(
                                  AppConfig.GetConfigInfo("JwtTokenOptions:SecurityKey")
                                  )), SecurityAlgorithms.HmacSha256)
                      );
            var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);

            return SUCCESS(new { userInfo = user, token = tokenStr });
        }

        /// <summary>
        /// 获取登录验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> CreateCode()
        {
            _code = VierificationCode.RandomText(4);
            //var imageBytes = VerifyCodeHelper.CreateByteByImgVerifyCode(_code, 100, 40);
            //// 将字节数组转换为Base64字符串
            //string base64String = "data:image/jpeg;base64," + Convert.ToBase64String(imageBytes);
            //return Ok(ApiResult.GetResult(ApiCord.ok, data: base64String));

            var codeImg = "data:image/png;base64," + VierificationCode.CreateBase64Image(_code);
            return SUCCESS(codeImg);
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="create"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> CreateUser(CreateUserInfoRequest create)
        {
            await _sysUser.CreateUser(create, null);
            return SUCCESS("操作成功");
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DeleteUserById(string id)
        {
            await _sysUser.DeleteUserById(id, null);
            return SUCCESS("操作成功");
        }

        /// <summary>
        /// 根据id获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserById(string id)
        {
            var result = await _sysUser.GetUserById(id);
            return SUCCESS(result);
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="update"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateUser(UpdateUserInfoRequest update)
        {
            await _sysUser.UpdateUser(update, null);
            return SUCCESS("操作成功");
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUserList([FromQuery] UserInfoQueryRequest query)
        {
            var result = await _sysUser.GetUserList(query);
            return SUCCESS(result);
        }
    }
}
